﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using DevExpress.XtraEditors;
using System;
using System.ComponentModel;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using XCI.Helper;
using XCI.Windows;

namespace XCI.Setting.Controls
{
    [ToolboxItem(false)]
    public partial class SettingTemplate : BaseUserControl
    {
        private SettingStoreManager _settingManager;
        private string _settingPrefix;

        public SettingTemplate()
        {
            InitializeComponent();
        }

        public void Init(SettingStoreManager settingManager, string settingPrefix)
        {
            _settingManager = settingManager;
            _settingPrefix = settingPrefix;
            _ = LoadDataAsync();
        }

        private async Task LoadDataAsync()
        {
            var list = await _settingManager.ListAsync();
            listBoxControl1.Items.BeginUpdate();
            listBoxControl1.Items.Clear();

            foreach (var item in list)
            {
                listBoxControl1.Items.Add(item);
            }
            listBoxControl1.Items.EndUpdate();
        }

        /// <summary>
        /// 验证
        /// </summary>
        protected bool Validation(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                MessageBoxHelper.ShowWarn("请输入配置名称");
                return false;
            }
            return true;
        }

        protected string GetSelectedName()
        {
            return listBoxControl1.SelectedValue as string;
        }

        private void ListBoxControl1_SelectedValueChanged(object sender, EventArgs e)
        {
            btnApply.Enabled = btnCopy.Enabled = btnDelete.Enabled =
                btnExport.Enabled = btnCopyToClipboard.Enabled = listBoxControl1.SelectedIndex > -1;
        }

        //private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        //{
        //    if (gridView1.OptionsView.ShowIndicator && e.Info.IsRowIndicator && e.RowHandle >= 0)
        //    {
        //        e.Info.DisplayText = (e.RowHandle + 1).ToString();
        //        e.Info.ImageIndex = -1;
        //    }
        //}

        private async void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var name = XtraInputBox.Show("请输入配置名称", "操作提示", string.Empty);
            if (!Validation(name)) return;
            await _settingManager.SaveAsync(name);
            await LoadDataAsync();
        }

        private async void btnCopy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var currentName = GetSelectedName();
            var newName = XtraInputBox.Show("请输入新配置名称", "操作提示", $"{currentName}-复制");
            if (!Validation(newName)) return;
            if (newName.Equals(currentName, StringComparison.OrdinalIgnoreCase))
            {
                MessageBoxHelper.ShowWarn("新名称和旧名称不能相同");
                return;
            }

            await _settingManager.CopyAsync(currentName, newName);
            await LoadDataAsync();
        }

        private async void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var currentName = GetSelectedName();
            if (MessageBoxHelper.ShowWarnYesNo("确定要删除选中的配置吗？") != DialogResult.Yes) return;
            await _settingManager.DeleteAsync(currentName);
            await LoadDataAsync();
        }

        private async void btnApply_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var currentName = GetSelectedName();
            if (MessageBoxHelper.ShowWarnYesNo("确定要应用选中的配置吗？") != DialogResult.Yes) return;
            await _settingManager.LoadAsync(currentName);
        }

        private async void btnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var currentName = GetSelectedName();
            saveFileDialog1.FileName = $"{_settingManager.Id}_{currentName}";
            if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
            var serverFile = _settingManager.CrreateServerFile(currentName);
            await serverFile.DownloadAsync();
            File.Copy(serverFile.LocalFilePath, saveFileDialog1.FileName, true);
            MessageBoxHelper.ShowMessage($"导出成功,文件保存在[{saveFileDialog1.FileName}]");
        }

        private async void BtnCopyToClipboard_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var currentName = GetSelectedName();
            var serverFile = _settingManager.CrreateServerFile(currentName);
            await serverFile.DownloadAsync();
            Clipboard.SetDataObject($"{_settingPrefix}{serverFile.LocalFilePath}", true);
            MessageBoxHelper.ShowMessage("配置信息已复制到剪贴板");
        }

        private async void BtnPasteFromClipboard_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            IDataObject data = Clipboard.GetDataObject();
            string errorMsg = "未发现有效的配置信息";
            if (data == null || !data.GetDataPresent(DataFormats.Text))
            {
                MessageBoxHelper.ShowMessage(errorMsg);
                return;
            }

            var dataText = data.GetData(DataFormats.Text) as string;
            if (string.IsNullOrEmpty(dataText) || dataText.IndexOf(_settingPrefix, StringComparison.Ordinal) == -1)
            {
                MessageBoxHelper.ShowMessage(errorMsg);
                return;
            }

            var path = dataText.Replace(_settingPrefix, string.Empty);
            var newName = XtraInputBox.Show("请输入新配置名称", "操作提示", string.Empty);
            if (!Validation(newName)) return;
            var serverFile = _settingManager.CrreateServerFile(newName);
            IOHelper.CreateDirectoryByPath(serverFile.LocalFilePath);
            File.Copy(path, serverFile.LocalFilePath, true);
            await serverFile.UploadAsync();
            await LoadDataAsync();
        }
    }
}
